<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>淘好货 - 结算</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#FF4400',
                        secondary: '#FFB800',
                        dark: '#333333',
                        light: '#F5F5F5',
                        muted: '#666666',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif']
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }

            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }

            .address-card {
                @apply border-2 rounded-lg p-4 transition-all duration-300 cursor-pointer;
            }

            .address-card.active {
                @apply border-primary bg-primary/5;
            }

            .coupon-card {
                @apply border rounded-lg overflow-hidden transition-all duration-300 cursor-pointer;
            }

            .coupon-card.active {
                @apply border-primary bg-primary/5;
            }
        }
    </style>
    <style>
        /* 自定义加载动画 */
        .spin {
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            from {
                transform: rotate(0deg);
            }
            to {
                transform: rotate(360deg);
            }
        }
    </style>
</head>
<body class="bg-gray-50 text-dark">
<div id="app">
    <!-- 导航栏 -->
    <navigation></navigation>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-8">
        <!-- 进度指示器 -->
        <div class="mb-12">
            <div class="flex items-center justify-between max-w-3xl mx-auto">
                <div class="flex flex-col items-center">
                    <div class="w-10 h-10 rounded-full bg-primary text-white flex items-center justify-center mb-2">
                        <i class="fa fa-shopping-cart"></i>
                    </div>
                    <span class="text-sm font-medium">购物车</span>
                </div>
                <div class="flex-1 h-1 bg-gray-200 mx-2">
                    <div class="h-full bg-primary" style="width: 50%"></div>
                </div>
                <div class="flex flex-col items-center">
                    <div class="w-10 h-10 rounded-full bg-primary text-white flex items-center justify-center mb-2">
                        <i class="fa fa-truck"></i>
                    </div>
                    <span class="text-sm font-medium text-primary font-bold">结算</span>
                </div>
                <div class="flex-1 h-1 bg-gray-200 mx-2"></div>
                <div class="flex flex-col items-center">
                    <div class="w-10 h-10 rounded-full bg-gray-200 text-muted flex items-center justify-center mb-2">
                        <i class="fa fa-credit-card"></i>
                    </div>
                    <span class="text-sm font-medium text-muted">支付</span>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- 订单信息 -->
            <div class="lg:col-span-2 space-y-8">
                <!-- 收货地址 -->
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h2 class="text-xl font-bold mb-6 flex items-center">
                        <i class="fa fa-map-marker text-primary mr-2"></i> 收货地址
                    </h2>

                    <!-- 地址列表 -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                        <div v-for="address in addresses" :key="address.id"
                             class="address-card"
                             :class="{ 'active': selectedAddress && selectedAddress.id === address.id }"
                             @click="selectAddress(address)">
                            <div class="flex justify-between items-start mb-2">
                                <span class="font-medium">{{ address.name }} {{ address.phone }}</span>
                                <span v-if="address.isDefault"
                                      class="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded">默认</span>
                            </div>
                            <p class="text-sm text-muted mb-2">{{ address.area }}{{ address.address }}</p>
                            <div class="flex justify-between text-xs text-gray-500">
                                <span>{{ address.area }}</span>
                                <div class="flex space-x-3">
                                    <button class="hover:text-primary">编辑</button>
                                    <button class="hover:text-red-500">删除</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 优惠券 -->
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h2 class="text-xl font-bold mb-6 flex items-center">
                        <i class="fa fa-ticket text-primary mr-2"></i> 优惠券
                    </h2>

                    <div class="flex items-center justify-between">
                        <div class="flex items-center">
                            <span class="text-sm text-gray-600">可用优惠券：</span>
                            <span class="text-primary font-medium ml-1">{{ (coupons || []).length }}张</span>
                        </div>
                        <button class="flex items-center text-primary text-sm font-medium" @click="showCoupons = true">
                            <span>选择优惠券</span>
                            <i class="fa fa-angle-right ml-1"></i>
                        </button>
                    </div>

                    <!-- 已选优惠券 -->
                    <div v-if="selectedCoupon"
                         class="mt-4 bg-primary/5 border border-primary/20 rounded-lg p-3 flex justify-between items-center">
                        <div class="flex items-center">
                            <i class="fa fa-ticket text-primary mr-2"></i>
                            <span class="font-medium">{{ selectedCoupon.name }}</span>
                            <span class="text-xs text-muted ml-2">{{ selectedCoupon.type === '满减' ? '满' + selectedCoupon.condition + '减' + selectedCoupon.discount : selectedCoupon.discount * 10 + '折' }}</span>
                        </div>
                        <button class="text-sm text-red-500" @click="removeCoupon">
                            <i class="fa fa-times-circle"></i> 移除
                        </button>
                    </div>

                    <!-- 优惠券选择面板 -->
                    <div v-if="showCoupons" class="mt-4 bg-gray-50 rounded-lg p-4">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-base font-medium">可用优惠券</h3>
                            <button class="text-sm text-gray-500" @click="showCoupons = false">关闭</button>
                        </div>

                        <div class="space-y-3 max-h-64 overflow-y-auto scrollbar-hide">
                            <!-- 优惠券循环展示 -->
                            <div v-for="coupon in coupons" :key="coupon.id"
                                 class="coupon-card"
                                 :class="{ 'active': selectedCoupon && selectedCoupon.id === coupon.id }"
                                 @click="selectCoupon(coupon)">
                                <div class="flex">
                                    <div class="w-20 bg-gradient-to-br from-green-500 to-green-600 text-white p-3 flex flex-col items-center justify-center">
                                        <span class="text-xs">{{ coupon.type }}</span>
                                        <span class="text-xl font-bold mt-1">
                                                {{ coupon.type === '满减' ? '¥' + coupon.discount : coupon.discount * 10 + '折' }}
                                            </span>
                                        <span class="text-xs mt-1">满{{ coupon.condition }}元可用</span>
                                    </div>
                                    <div class="flex-1 p-3">
                                        <div class="flex justify-between">
                                            <span class="font-medium">{{ coupon.name }}</span>
                                            <span class="text-xs text-primary"
                                                  v-if="selectedCoupon && selectedCoupon.id === coupon.id">
                                                    已选择
                                                </span>
                                            <span class="text-xs text-gray-400" v-else>
                                                    点击选择
                                                </span>
                                        </div>
                                        <p class="text-xs text-gray-500 mt-1">有效期至：{{ coupon.expireDate }}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 商品列表（仅显示选中商品） -->
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h2 class="text-xl font-bold mb-6 flex items-center">
                        <i class="fa fa-shopping-basket text-primary mr-2"></i> 商品列表
                    </h2>

                    <div class="space-y-4">
                        <!-- 使用 computed 筛选选中商品 -->
                        <div v-for="item in selectedCartItems" :key="item.id"
                             class="flex pb-4 border-b border-gray-100">
                            <img :src="item.image || 'https://picsum.photos/200/200'" alt="商品图片"
                                 class="w-20 h-20 object-cover rounded-md">
                            <div class="ml-4 flex-1">
                                <h3 class="text-sm font-medium text-gray-900 line-clamp-2">{{ item.product_name }}</h3>
                                <div class="flex justify-between items-center mt-2">
                                    <div>
                                        <span class="text-primary font-medium">¥{{ formatPrice(item.price) }}</span>
                                        <span class="text-gray-500 text-sm ml-2">x{{ item.quantity }}</span>
                                    </div>
                                    <span class="text-gray-600">小计: ¥{{ formatPrice(item.price*item.quantity) }}</span>
                                </div>
                            </div>
                        </div>

                        <!-- 无选中商品提示 -->
                        <div v-if="selectedCartItems.length === 0" class="py-8 text-center">
                            <i class="fa fa-shopping-cart text-gray-300 text-5xl mb-4"></i>
                            <p class="text-gray-500">
                                请在购物车中选择要结算的商品，将在 <span
                                    class="text-primary font-medium animate-pulse">{{ redirectCountdown }}</span> 秒后自动跳转
                            </p>
                            <a href="/cart" class="inline-block mt-4 text-primary font-medium hover:underline">
                                <i class="fa fa-arrow-left mr-1"></i> 立即返回购物车
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 订单摘要 -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl shadow-md p-6 sticky top-24">
                    <h2 class="text-xl font-bold mb-6 flex items-center">
                        <i class="fa fa-calculator text-primary mr-2"></i> 订单摘要
                    </h2>

                    <!-- 价格汇总 -->
                    <div class="space-y-3 text-sm mb-6">
                        <div class="flex justify-between">
                            <span class="text-gray-600">商品总价</span>
                            <span>¥{{ formatPrice(subtotal) }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">运费</span>
                            <span v-if="subtotal > 0">¥{{ formatPrice(shippingFee) }}</span>
                            <span v-else>¥0.00</span>
                        </div>
                        <div class="flex justify-between" v-if="selectedCoupon">
                            <span class="text-gray-600">优惠券</span>
                            <span class="text-green-500">-¥{{ formatPrice(couponDiscount) }}</span>
                        </div>
                        <div class="border-t border-gray-100 pt-3 flex justify-between font-medium">
                            <span>实付款</span>
                            <span class="text-lg text-primary font-bold">¥{{ formatPrice(totalAmount) }}</span>
                        </div>
                    </div>

                    <!-- 提交订单按钮 -->
                    <button
                            class="w-full py-3 bg-primary text-white rounded-lg font-medium hover:bg-primary/90 transition-colors"
                            @click="submitOrder"
                            :disabled="isSubmitting || selectedCartItems.length === 0 || !selectedAddress"
                    >
                        <span v-if="!isSubmitting">
                            <i class="fa fa-check mr-1"></i> 提交订单
                        </span>
                        <span v-else class="flex items-center justify-center space-x-2">
                            <div class="h-4 w-4 border-2 border-solid border-primary border-t-transparent rounded-full spin"></div>
                            提交中...
                        </span>
                    </button>

                    <!-- 加载遮罩层 -->
                    <div v-if="isSubmitting" class="fixed inset-0 bg-black/30 z-50 flex items-center justify-center">
                        <div class="bg-white rounded-lg p-8 shadow-xl">
                            <div class="flex flex-col items-center">
                                <div class="h-16 w-16 border-8 border-t-primary border-b-transparent rounded-full spin mb-4"></div>
                                <h3 class="text-xl font-bold text-gray-800 mb-2">正在处理您的订单</h3>
                                <p class="text-gray-600 text-center">请保持页面不要关闭，我们正在为您准备支付</p>
                            </div>
                        </div>
                    </div>

                    <!-- 支付方式说明 -->
                    <div class="mt-4 text-xs text-gray-500 text-center">
                        <p>支持苹果支付、微信支付、信用卡</p>
                        <div class="flex justify-center space-x-3 mt-2">
                            <i class="fa fa-apple text-gray-500"></i>
                            <i class="fa fa-weixin text-green-500"></i>
                            <i class="fa fa-credit-card text-gray-500"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <app-footer></app-footer>
</div>
<script src="/static/js/vue.js"></script>
<script src="/static/js/top.js"></script>
<script src="/static/js/foot.js"></script>
<script src="/static/js/common.js"></script>
<script src="/static/js/message.js"></script>
<script>
    // 地址数据
    const addresses = [
        {
            id: 1,
            name: '张三',
            phone: '13800138000',
            area: '北京市海淀区',
            address: '中关村大街1号 科技大厦15层1501室',
            isDefault: true
        },
        {
            id: 2,
            name: '李四',
            phone: '13900139000',
            area: '上海市浦东新区',
            address: '张江高科技园区博云路2号 浦软大厦8层802室',
            isDefault: false
        }
    ];

    // 优惠券数据
    const coupons = [
        {
            id: 1,
            type: '满减',
            discount: 50,
            condition: 299,
            name: '满减优惠券',
            expireDate: '2025-06-30'
        },
        {
            id: 2,
            type: '折扣',
            discount: 0.9, // 9折
            condition: 199,
            name: '折扣优惠券',
            expireDate: '2025-05-31'
        }
    ];

    // Vue实例
    new Vue({
        el: '#app',
        data: {
            util,
            addresses: addresses,
            coupons: coupons,
            selectedAddress: addresses.find(a => a.isDefault), // 默认选中第一个地址
            selectedCoupon: null,
            showCoupons: false,
            cartItems: JSON.parse(localStorage.getItem('cart')) || [], // 从本地存储获取购物车数据
            redirectCountdown: 5, // 倒计时秒数
            countdownTimer: null, // 定时器ID
            isSubmitting: false // 提交状态
        },
        computed: {
            // 计算属性：筛选选中的商品
            selectedCartItems() {
                return this.cartItems.filter(item => item && item.selected);
            },
            subtotal() {
                return this.selectedCartItems.reduce((total, item) => {
                    return total + (item.price * item.quantity);
                }, 0);
            },
            shippingFee() {
                return this.subtotal >= 299 ? 0 : Math.max(0, this.subtotal > 0 ? 10 : 0);
            },
            couponDiscount() {
                if (!this.selectedCoupon) return 0;
                const subtotal = this.subtotal;
                if (this.selectedCoupon.type === '满减' && subtotal >= this.selectedCoupon.condition) {
                    return this.selectedCoupon.discount;
                } else if (this.selectedCoupon.type === '折扣' && subtotal >= this.selectedCoupon.condition) {
                    return subtotal * (1 - this.selectedCoupon.discount);
                }
                return 0;
            },
            totalAmount() {
                return this.subtotal + this.shippingFee - this.couponDiscount;
            }
        },
        methods: {
            // 启动倒计时
            startCountdown() {
                // 清除现有定时器，避免重复启动
                this.stopCountdown();

                // 重置倒计时
                this.redirectCountdown = 5;

                // 设置新的定时器
                this.countdownTimer = setInterval(() => {
                    if (this.redirectCountdown <= 0) {
                        this.stopCountdown();
                        window.location.href = '/cart'; // 跳转购物车
                    } else {
                        this.redirectCountdown--;
                    }
                }, 1000);
            },

            // 停止倒计时
            stopCountdown() {
                if (this.countdownTimer) {
                    clearInterval(this.countdownTimer);
                    this.countdownTimer = null;
                }
            },

            // 选择地址
            selectAddress(address) {
                this.selectedAddress = address;
            },

            // 选择优惠券
            selectCoupon(coupon) {
                this.selectedCoupon = coupon;
                this.showCoupons = false;
            },

            // 移除优惠券
            removeCoupon() {
                this.selectedCoupon = null;
            },

            // 安全格式化价格
            formatPrice(price) {
                return (parseFloat(price) || 0).toFixed(2);
            },
            // 提交订单
            async submitOrder() {
                // 防止重复提交
                if (this.isSubmitting) return;

                // 验证逻辑
                if (this.selectedCartItems.length === 0) {
                    message.error('请选择要结算的商品');
                    return;
                }

                if (!this.selectedAddress) {
                    message.error('请选择收货地址');
                    return;
                }

                // 开始提交状态
                this.isSubmitting = true;

                try {
                    // 收集购物车项 ID
                    const cartIds = this.selectedCartItems.map(item => item.id);
                    // 收集地址信息
                    const recipientName = this.selectedAddress.name;
                    const recipientPhone = this.selectedAddress.phone;
                    const shippingAddress = `${this.selectedAddress.area} ${this.selectedAddress.address}`;
                    //收集订单金额信息
                    const subtotal = this.subtotal;
                    const totalAmount = this.totalAmount;
                    const shippingFee = this.shippingFee;
                    const couponDiscount = this.couponDiscount;

                    // 发送 POST 请求到创建订单接口
                    const response = await fetch('/orders', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            cart_ids: cartIds,
                            recipient_name: recipientName,
                            recipient_phone: recipientPhone,
                            shipping_address: shippingAddress,
                            subtotal: subtotal,
                            total_amount: totalAmount,
                            shipping_fee: shippingFee,
                            coupon_discount: couponDiscount
                        })
                    });

                    if (response.ok) {
                        const res = await response.json();
                        const orderId = res.order_id;
                        // 订单提交成功
                        message.success('订单提交成功！即将跳转到支付页面');
                        // 模拟延迟
                        setTimeout(() => {
                            // 跳转到支付页面
                            window.location.href = `/pay?order_id=${orderId}`;
                        }, 2000);

                    } else {
                        const error = await response.json();
                        message.error(error.message);
                    }

                } catch (error) {
                    message.error('网络错误，请稍后重试');
                } finally {
                    // 结束提交状态
                    this.isSubmitting = false;
                }
            }
        },
        created() {
            util.store.set("return-url", location.href);
            if (this.util.isLogin()) {
                // 页面加载时初始化数据
                this.cartItems = JSON.parse(localStorage.getItem('cart')) || [];
                // 检查是否有选中的商品，没有则启动倒计时
                if (this.selectedCartItems.length === 0) {
                    this.startCountdown();
                }
            } else location.href = '/login';
        },
        beforeDestroy() {
            // 组件销毁前清除定时器，避免内存泄漏
            this.stopCountdown();
        }
    });
</script>
</body>
</html>